package servlet;

import com.alibaba.druid.support.json.JSONUtils;
import entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JdbcUtilsV1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    // 接收请求，接收参数；处理业务逻辑；操作数据库

    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        
        if (username != null && password != null) {
            try {
                // 调用业务层
                User user =  userService.login(username,password);
                if (user != null) {
                    // 登录成功
                    req.getSession().setAttribute("user", user);
                    req.getRequestDispatcher("/index.jsp").forward(req, resp);
                } else {
                    // 登录失败
                    req.getRequestDispatcher("/login.jsp").forward(req, resp);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
